<?php

namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Type;

/**
 * Class SoundController
 * @package Wintel\RestBundle\Controller
 */
class SoundController extends Controller
{
    /**
     * 上传语音
     * @param Request $request
     * @return JsonResponse
     */
    public function uploadAction(Request $request)
    {
        $msg = $this->get('icsoc_data.model.sound')->upload($request);
        return new JsonResponse($msg);
        /** @var \Doctrine\DBAL\Connection $conn*/
        /*** 老版本的写法
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code =  $request->get('vcc_code', 0);
        $name = $request->get('name', '');
        $remark = $request->get('remark', '');
        $sound = $request->files->get("sound");

        //vcc_code 验证
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //验证name
        $msg = $this->get('validator.custom')->isEmptyName($name, 403, '录音名称为空');
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //验证是否上传文件；
        if (empty($sound)) {
            return new JsonResponse(array('code'=>409, 'message'=>'没有上传语音'));
        }

        //验证 sound
        $valiFile = new File();
        $valiFile->mimeTypes = array('audio/x-wav');
        $error_list = $this->get("validator")->validateValue($sound, $valiFile);
        if (count($error_list) > 0) {
            $error_msg = $error_list[0]->getMessage();
            return new JsonResponse(array('code'=>404, 'message'=>$error_msg));
        } else {
            //开始上传文件
            $maxid = $conn->fetchColumn(
                'SELECT max(id) '.
                'FROM win_sounds '.
                'WHERE vcc_id = :vcc_id ',
                array('vcc_id'=>$vid)
            );
            $maxid = $maxid ? $maxid+1 : 1;
            $filename = 'sound'.$vid.'_'.$maxid.'.wav';
            $filepath = '/var/sounds/'.$vid.'/';
            try {
                $target= $sound->move($filepath, $filename);
            } catch (Exception $e) {
                $msg = $sound->getErrorMessage();
                $ret = array('code'=>405, 'message'=>$msg);
                return new JsonResponse($ret);
            }
            $data = array();
            $data['address'] = $target->getPathname();
            $data['sounds_address'] = $this->container->getParameter('sound_address').$vid.'/'.$filename;
            $result = exec("file ".$target->getPathname());
            if (preg_match('/^(.)+(WAVE audio)(.)+(16 bit)(.)+(mono 8000 Hz)(.)*$/', $result)) {
                /* 调用远程system文件拷贝语音 *
                $win_ip  = $this->container->getParameter('win_ip');
                $win_web_port = $this->container->getParameter('win_web_port');
                $win_system_name = $this->container->getParameter('win_system_name');
                //$exec_result = file_get_contents("http://$win_ip:$win_web_port/$win_system_name/system.php?act=sound&vcc_id=$vid&address=".$target->getPathname());
                $ch = curl_init("http://$win_ip:$win_web_port/$win_system_name/system.php?act=sound");
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                if (class_exists('CurlFile')) {
                    $file = new \CURLFile($data['address']);
                } else {
                    $file = '@'.$data['address'];
                }
                curl_setopt($ch, CURLOPT_POSTFIELDS, array(
                    'vcc_id' => $vid,
                    'sound' => $file,
                ));
                $exec_result = curl_exec($ch);
                $exec_result = json_decode($exec_result, true);
                $code = isset($exec_result['code']) ? $exec_result['code'] : 0;
                //var_dump($exec_result);
                if ($code == 200) {
                    $data['vcc_id'] = $vid;
                    $data['name'] = $name;
                    $data['remark'] = $remark;
                    $data['vcc_code'] = $vcc_code;
                    $data['add_time'] = date("Y-m-d H:i:s");
                    $conn->insert('win_sounds', $data);
                    $sound_id = $conn->lastInsertId();
                    if ($sound_id) {
                        $ret = array(
                            'code' => 200,
                            'message' => 'ok',
                        );
                        return new JsonResponse($ret);
                    } else {
                        $ret = array(
                            'code' => 408,
                            'message' => '数据保存失败',
                        );
                        return new JsonResponse($ret);
                    }
                } else {
                    $ret = array(
                        'code' => 407,
                        'message' => '语音拷贝到通信服务器失败',
                    );
                    return new JsonResponse($ret);
                }
            } else {
                $ret = array(
                    'code' => 406,
                    'message' => '语音文件格式不正确（wav)',
                );
                return new JsonResponse($ret);
            }

        }*/
    }

    /**
     * @param $vcc_code
     * @param $info
     * @return JsonResponse
     * 获取 所有语音信息
     */
    public function listAction($vcc_code, $info)
    {
        /** @var \Doctrine\DBAL\Connection $conn*/
        $conn = $this->get("doctrine.dbal.default_connection");

        //vcc_code 验证
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 403, 'message'=>'info格式非json'));
            }
        }
        //查出总计的条数
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_sounds '.
            'WHERE vcc_id = :vid ',
            array('vid'=>$vid)
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_sounds', $addInfo);
        $list = $conn->fetchAll(
            'SELECT id,name,remark,address,sounds_address,add_time '.
            'FROM win_sounds '.
            'WHERE vcc_id = :vcc_id '.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vcc_id' => $vid)
        );
        return new JsonResponse(array('code'=>200, 'message'=>'ok', 'total' => $count,'data'=>$list));
    }

    /**
     * @param $vcc_code
     * @param $sound_id
     * @return JsonResponse
     * 删除语音接口
     */
    public function deleteAction($vcc_code, $sound_id)
    {
        /** @var \Doctrine\DBAL\Connection $conn*/
        $conn = $this->get("doctrine.dbal.default_connection");
        //vcc_code 验证
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }
        $type = new Type(array('type'));
        $type->type = 'numeric';
        $type->message = "sound_id不是数字";
        //批量
        $sound_arr = json_decode($sound_id);
        $sound_arr = json_last_error() || !is_array($sound_arr) ? array((int)$sound_id) : $sound_arr;
        if (empty($sound_arr)) {
            return new JsonResponse(array('code'=>405, 'message'=>'sound_id为空'));
        }

        $errorMsg = array();
        foreach ($sound_arr as $sound_id) {
            $error_list = $this->get('validator')->validateValue($sound_id, $type);
            if (count($error_list) > 0) {
                $errorMsg[] = array('code'=>403, 'message'=>$error_list[0]->getMessage(), 'sound_id'=>$sound_id);
                continue;
            }
            $number =  $conn->delete("win_sounds", array('id' => $sound_id, 'vcc_code'=>$vcc_code));
            if ($number == 0) {
                $errorMsg[] = array('code'=>404, 'message'=>"sound_id:$sound_id 记录不存在",'sound_id'=>$sound_id);
            } else {
                $errorMsg[] = array('code'=>200, 'message'=>"OK",'sound_id'=>$sound_id);
            }
        }
        return new JsonResponse(array('code'=>500, 'message'=>'总结果', 'data'=>$errorMsg));
    }


    /**
     * 播放语音接口
     * @param $vcc_code
     * @param $sound_id
     * @return JsonResponse|Response
     *
     */
    public function playSoundAction($vcc_code, $sound_id)
    {
        //vcc_code 验证
        $msg = $vcc_id = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        if (empty($sound_id)) {
            $ret = array(
                'code' => 403,
                'message' => 'sound_id为空',
            );
            return new JsonResponse($ret);
        }
        if (!is_numeric($sound_id)) {
            $ret = array(
                'code' => 404,
                'message' => 'sound_id格式不对，要求为数字',
            );
            return new JsonResponse($ret);
        }

        /** @var \Doctrine\DBAL\Connection $conn*/
        $conn = $this->get('doctrine.dbal.default_connection');
        //$record_url = $this->container->getParameter('record_url');
        $recordFile = $conn->fetchColumn(
            'SELECT address FROM win_sounds WHERE vcc_id = :vcc_id AND id = :sound_id LIMIT 1',
            array(
                'vcc_id' => $vcc_id,
                'sound_id' => $sound_id,
            )
        );
        if (empty($recordFile) || !file_exists($recordFile)) {
            return new JsonResponse(array('code'=>'405', 'message'=>'语音文件不存在'));
        }
        //$remoteFile = $record_url.$recordFile;
        //$headers = get_headers($remoteFile);
//        $headers = get_headers($recordFile);
//        $remoteFileSize = 0;
//        foreach ($headers as $header) {
//            $headerString = explode(':', $header);
//            if ($headerString[0] == 'Content-Length') {
//                $remoteFileSize = $headerString[1];
//                break;
//            }
//        }
        $fileType = $this->get('help.function')->getSoundFileType($recordFile);
        //return new Response(file_get_contents($record_url.$recordFile), 200, array(
        return new Response(file_get_contents($recordFile), 200, array(
            'Pragma' => 'Public',
            'Expires' => 0,
            'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-type' => $fileType,
            'Content-Length' => filesize($recordFile),
            'Content-Transfer-Encoding' => 'binary',
            'Accept-Ranges' => 'bytes',
            'Content-Disposition' => 'attachment;filename='.basename($recordFile)
        ));
    }
}
